from datetime import timedelta
from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordRequestForm
from sqlmodel import Session
from app.schemas.user import Token, UserRead, UserCreate
from app.api.deps import get_db
from app.core import security, config
from app.crud.user import get_user_by_email, create_user, authenticate_user

router = APIRouter()

@router.post("/login", response_model=Token)
def login(form_data: OAuth2PasswordRequestForm = Depends(), db: Session = Depends(get_db)):
    user = authenticate_user(db, form_data.username, form_data.password)
    if not user:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Incorrect email or password")
    token = security.create_access_token(str(user.id), timedelta(minutes=config.settings.ACCESS_TOKEN_EXPIRE_MINUTES))
    return {"access_token": token, "token_type": "Bearer"}

@router.post("/signup", response_model=UserRead)
def signup(payload: UserCreate, db: Session = Depends(get_db)):
    email = str(payload.email)
    if get_user_by_email(db, email):
        raise HTTPException(status_code=400, detail="Email already registered")
    return create_user(db, email, payload.password)
